package com.tarena.lbs.activity.service.impl;

import com.github.pagehelper.PageInfo;
import com.tarena.lbs.activity.dao.repository.ActivityRepository;
import com.tarena.lbs.activity.enums.ActivityStatusEnum;
import com.tarena.lbs.activity.pojo.param.ActivityAddParam;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.base.protocol.enums.ErrorCodeSupport;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.encoder.JwtEncoder;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.utils.PageConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author 周恒宇
 * @date 6/10
 */
@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityRepository activityRepository;
    @DubboReference
    AttachApi attachApi;
    @Override
    public PageResult<ActivityVO> pageList() throws BusinessException {
        log.info("查询活动分页列表");
        PageInfo<ActivityPO> pageInfo = activityRepository.pageList();

        // 使用Stream转换PO到VO
        List<ActivityVO> activityVOS = pageInfo.getList().stream()
                .map(po -> {
                    ActivityVO vo = new ActivityVO();
                    BeanUtils.copyProperties(po, vo);
                    return vo;
                })
                .collect(Collectors.toList());

        return PageConverter.convert(pageInfo, activityVOS);
    }

    @Override
    public void activitySave(ActivityAddParam activityAddParam) throws BusinessException {
        log.info("保存活动信息，参数: {}", activityAddParam);
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if(userPrinciple == null){
            throw new BusinessException(ActivityStatusEnum.USER_NOT_LOGIN);
        }

        if (userPrinciple.getRole() == Roles.USER) {
            throw new BusinessException(ActivityStatusEnum.PURVIEW_NOT_ENOUGH);
        }

        // 区分新增/更新逻辑
        if (activityAddParam.getId() == null) {
            handleCreate(activityAddParam);
        } else {
            handleUpdate(activityAddParam);
        }
    }

    private void handleCreate(ActivityAddParam param) {
        ActivityPO po = new ActivityPO();
        BeanUtils.copyProperties(param, po);
        po.setId(null); // 确保ID自增
        po.setCreateAt(new Date());
        activityRepository.activitySave(po);
        log.info("新增活动成功，ID: {}", po.getId());
    }

    private void handleUpdate(ActivityAddParam param) throws BusinessException {
        ActivityPO existingPo = activityRepository.selectById(param.getId());
        if (existingPo == null) {
            throw new BusinessException(ActivityStatusEnum.NOT_EXITS);
        }

        // 只更新允许修改的字段
        BeanUtils.copyProperties(param, existingPo, "id", "createAt", "createBy");
        existingPo.setUpdateAt(new Date());
        activityRepository.activitySave(existingPo);
        log.info("更新活动成功，ID: {}", param.getId());
    }

    @Override
    public ActivityVO activityDetail(Integer id) throws BusinessException {
        log.info("查询活动详情，ID: {}", id);
        ActivityPO po = Optional.ofNullable(activityRepository.selectById(id))
                .orElseThrow(() -> new BusinessException(ActivityStatusEnum.NOT_EXITS));

        ActivityVO vo = new ActivityVO();
        BeanUtils.copyProperties(po, vo);

        // 获取附件信息（根据实际业务调整参数）
        if (po.getImgIds() != null && !po.getImgIds().isEmpty()) {
            List<Integer> imgIds = Arrays.stream(po.getImgIds().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());

            // 假设imgIds是存储附件ID的字段
            List<AttachDTO> attachDTO = attachApi.batchGetAttachInfo(imgIds,1);
            List<String> imgPics = attachDTO.stream().map(AttachDTO::getFileUuid).collect(Collectors.toList());
            vo.setImgPics(imgPics); // 第二个参数表示系统模块标识
        }
        return vo;
    }
}